package org.batatasframework.chart.data;

import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;

import org.batatasframework.chart.ChartDefinition;
import org.batatasframework.chart.ChartRow;
import org.batatasframework.chart.columns.ChartColumn;
import org.batatasframework.chart.columns.ChartColumnAxis;

public class ChartData {
	
	Object[][] data;
	Object[] summary;
	
	final ChartColumnAxis axis;
	final ChartDefinition definition;
	
	//重新分配空间位置
	final ChartInitializer initializer = new ChartInitializer();
		
	public int getRowspan(){
		return Math.max(axis.rowspan(), definition.getRowspan());
	}
	
	public ChartData finish(){
		//进行排序
		final int size = axis.size();
		
		Arrays.sort(data, new Comparator<Object[]>(){

			@Override
			public int compare(Object[] o1, Object[] o2) {
				int value = 0;
				for(int i = 0; i < size && value == 0; i++){
					value = o1[i].toString().compareTo(o2[i].toString());
				}
				return value;
			}
			
		});
		return this;
	}
	
	public ChartData(ChartColumnAxis axis, ChartDefinition definition){
		this.axis = axis;
		this.definition = definition;
		
		this.axis.initialize(initializer);
		for(ChartColumn column : definition){
			column.initialize(initializer);
		}
	}
	
	public void addData(Collection<ChartRow> rowData){
		//还要处理汇总的情况
		data = new Object[rowData.size()][];
		ChartRow summaryRow = definition.newRow();
		
		int i = 0;
		for(ChartRow row : rowData){
			
			//累计合计行
			summaryRow.add(row);
			
			//对数据进行读取
			data[i++] = row.writeRow();
		}
		
		//读取合计行
		this.summary = summaryRow.writeData();
	}
}
